<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */
namespace app\api\model\dao;

use app\library\Flag;
use think\Model;
use think\Db;

class NoteReplyReply extends Model
{
    protected $table = 'note_reply_reply';

    protected $pk = 'id';

    /**
     * 回复帖子
     *
     */
    public function add($arrInput)
    {

        unset($arrInput[$this->pk]);

        $this->data($arrInput);
        $this->save();
        return $this->data[$this->pk];
    }

    /**
     * 删除帖子回复回复
     *
     */
    public function del($id)
    {

        if (empty($arrInput['id'])) {
            return false;
        }

        $conds = [
            'id' => ['=', $id]
        ];

        return Db::table($this->table)->where($conds)->delete();
    }

    /**
     * 标记已读
     *
     */
    public function read($reply_id, $userid = 0)
    {

        $conds = [
            'reply_id' => ['=', $reply_id]
        ];

        if ($userid) {
            $conds['recv_userid'] = ['=', $userid];
        }

        $data = [
            'status' => 1,
        ];

        return Db::table($this->table)->where($conds)->update($data);
    }

    /**
     * 标记已读
     *
     */
    public function clear($userid)
    {

        $conds = [
            'recv_userid' => ['=', $userid],
            'status' => ['=', 0],
        ];

        $data = [
            'status' => 1,
        ];

        return Db::table($this->table)->where($conds)->update($data);
    }

    /**
     * 获取列表
     *
     */
    public function getList($conds = [], $fields = [], $offset = 0, $limit = 10000, $orderby = '')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';

        $arrField = [];
        foreach ($fields as $val) {
            if (in_array($val, $this->field)) {
                $arrField[] = $val;
            }
        }
        empty($arrField) && $arrField = $this->field;

        return Db::table($this->table)->where($arrCond)->limit($offset, $limit)->order($orderby)->field($arrField)->select();
    }

    public function getHotList($note_id, $offset = 0, $limit = 10)
    {
        $sql = sprintf('select reply_id,count(*) as reply_cnt from %s where note_id = %d  group by reply_id order by reply_cnt desc limit %d,%d', $this->table, $note_id, $offset, $limit);
        return Db::table($this->table)->query($sql);
    }

    /**
     * 根据条件获取回帖数
     *
     */
    public function getNoteReplyReplyCountByConds($arrCond, $group = '')
    {
        return Db::table($this->table)->where($arrCond)->group($group)->count();
    }

}
